package com.hqyj.springBoot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@WebListener
public class LogFileDestroyListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogFileDestroyListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("============= ServletContextListener Initialized ============");
        //拿到目标文件夹,看看目标文件夹是否存在
        String logBaseFolder = "/var/log";
        File destFolder = new File(logBaseFolder);
        if (!destFolder.exists()){
            return;
        }

        //拿到当前日期格式化字符串
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = dtf.format(LocalDate.now());

        //将目标文件夹的日志文件进行遍历,获取文件的名字,如果文件名包含当前日期字符串,不做删除,反之删除
        File[] files = destFolder.listFiles();
        for (File file : files) {
            String fileName = file.getName();
            if (!fileName.contains(currentDate)){
                file.delete();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("============= ServletContextListener Destroyed =============");

    }
}
